package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.CmnBookMerchantAdapter;
import com.hemaapp.yjnh.listener.OnItemClickListener;
import com.hemaapp.yjnh.bean.AdImage;
import com.hemaapp.yjnh.bean.Client;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.view.ImageCarouselBanner;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.util.XtomWindowSize;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;

/**
 * 走走
 *
 * @author GuiyouZhang
 */
public class ZouzouActivity extends BaseActivity implements OnClickListener {

    @Bind(R.id.image_carousel_banner)
    ImageCarouselBanner imageCarouselBanner;
    @Bind(R.id.tv_scenic)
    TextView tvScenic;
    @Bind(R.id.line_scenic)
    View lineScenic;
    @Bind(R.id.layout_scenic)
    RelativeLayout layoutScenic;
    @Bind(R.id.tv_camping)
    TextView tvCamping;
    @Bind(R.id.line_camping)
    View lineCamping;
    @Bind(R.id.layout_camping)
    RelativeLayout layoutCamping;
    @Bind(R.id.tv_motor_homes)
    TextView tvMotorHomes;
    @Bind(R.id.line_motor_homes)
    View lineMotorHomes;
    @Bind(R.id.layout_motor_homes)
    RelativeLayout layoutMotorHomes;
    private ImageButton titleLeftBtn;
    private TextView tvCity;
    private ImageView titleSearch;
    private TextView title_text;
    private RefreshLoadmoreLayout layoutRefresh;
    private XtomListView listView;

    private View headerView;
    private View footer;

    private ArrayList<AdImage> imgs = new ArrayList<>();
    private ArrayList<Client> datas = new ArrayList<>();//推荐的露营地商家
    private CmnBookMerchantAdapter adapter;
    private String keytype = "9";//7：推荐的露营地; 8：推荐的房车; 9：推荐的景区商家
    private String role = "13";//商家类型:11走走露营商家；12走走房车商家；13走走景区商家；
    private int page = 0;
    private String city;//当前选择的城市
    private String lat;
    private String lng;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_zouzou);
        super.onCreate(savedInstanceState);
        //2016.10.31 start 为了和iOS一致，这里田家、乐乐、走走、农需的地区都单独保存
//		city = XtomSharedPreferencesUtil.get(mContext, "city");
        city = XtomSharedPreferencesUtil.get(mContext, "city_zouzou");
        if (isNull(city)) {
            city = XtomSharedPreferencesUtil.get(mContext, "city");
        }
        //2016.10.31 end 为了和iOS一致，这里田家、乐乐、走走、农需的地区都单独保存
        lat = XtomSharedPreferencesUtil.get(mContext, "lat");
        lng = XtomSharedPreferencesUtil.get(mContext, "lng");
        init();
    }

    private void init() {
        headerView = LayoutInflater.from(mContext).inflate(R.layout.header_activity_zouzou, null);
        ButterKnife.bind(this, headerView);
        layoutScenic.setOnClickListener(this);
        layoutCamping.setOnClickListener(this);
        layoutMotorHomes.setOnClickListener(this);
        tvScenic.setCompoundDrawablesWithIntrinsicBounds(
                getResources().getDrawable(R.drawable.zouzou_scenic), null, null, null);
        footer = LayoutInflater.from(mContext).inflate(R.layout.footer_load_more, null);
        footer.setOnClickListener(this);
        listView.addHeaderView(headerView);
        listView.addFooterView(footer);
        tvCity.setText(city);
        if (city.length() > 1)
            getNetWorker().ModelADList("2", city.substring(0, city.length() - 1));
        getMerchantList();
    }

    /**
     * 获取商家列表
     * role	商家类型:11走走露营商家；12走走房车商家；
     */
    private void getMerchantList() {
        if (isNull(city)) {
            XtomToastUtil.showShortToast(mContext, "定位失败，请稍后再试");
        } else {
            User user = getApplicationContext().getUser();
            String token = user==null?"":user.getToken();
            getNetWorker().clientList(token, keytype, city, "1", "1", role, page + "", lat, lng);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.tv_city:
                Intent itProvince = new Intent(mContext, CityActivity.class);
                itProvince.putExtra("type", 1);
                itProvince.putExtra("parent_id", "-1");
                startActivityForResult(itProvince, 1);
                break;
            case R.id.title_right_img:
                Intent itSearch = new Intent(mContext, SearchActivity.class);
                itSearch.putExtra("type", 10);
                itSearch.putExtra("assort", "走走");
                startActivity(itSearch);
                break;
            case R.id.tv_load_more:
                Intent itDistrict = new Intent(mContext, CmnBookMerchantListActivity.class);
                itDistrict.putExtra("keytype", keytype);
                String city = XtomSharedPreferencesUtil.get(mContext, "city");
                itDistrict.putExtra("keyid", city);
                if (keytype.equals("7")) {//7：推荐的露营地; 8：推荐的房车; 9：推荐的景区商家
                    itDistrict.putExtra("title", "露营地列表");
                    itDistrict.putExtra("role", "11");
                }else if (keytype.equals("8")) {
                    itDistrict.putExtra("title", "房车列表");
                    itDistrict.putExtra("role", "12");
                }else {
                    itDistrict.putExtra("title", "景区列表");
                    itDistrict.putExtra("role", "13");
                }
                startActivity(itDistrict);
                break;
            case R.id.layout_scenic:
                reset();
                tvScenic.setCompoundDrawablesWithIntrinsicBounds(
                        getResources().getDrawable(R.drawable.zouzou_scenic), null, null, null);
                tvScenic.setTextColor(getResources().getColor(R.color.theme_orange));
                lineScenic.setVisibility(View.VISIBLE);
                keytype = "9";
                role = "13";
                adapter.setType(0);
                page = 0;
                getMerchantList();
                break;
            case R.id.layout_camping:
                reset();
                tvCamping.setCompoundDrawablesWithIntrinsicBounds(
                        getResources().getDrawable(R.drawable.zouzou_camping), null, null, null);
                tvCamping.setTextColor(getResources().getColor(R.color.theme_orange));
                lineCamping.setVisibility(View.VISIBLE);
                keytype = "7";
                role = "11";
                adapter.setType(1);
                page = 0;
                getMerchantList();
                break;
            case R.id.layout_motor_homes:
                reset();
                tvMotorHomes.setCompoundDrawablesWithIntrinsicBounds(
                        getResources().getDrawable(R.drawable.zouzou_motor_homes), null, null, null);
                tvMotorHomes.setTextColor(getResources().getColor(R.color.theme_orange));
                lineMotorHomes.setVisibility(View.VISIBLE);
                keytype = "8";
                role = "12";
                adapter.setType(0);
                page = 0;
                getMerchantList();
                break;
        }
    }

    private void reset() {
        tvScenic.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        tvScenic.setTextColor(getResources().getColor(R.color.text_color_dark_grey));
        lineScenic.setVisibility(View.GONE);
        tvCamping.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        tvCamping.setTextColor(getResources().getColor(R.color.text_color_dark_grey));
        lineCamping.setVisibility(View.GONE);
        tvMotorHomes.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        tvMotorHomes.setTextColor(getResources().getColor(R.color.text_color_dark_grey));
        lineMotorHomes.setVisibility(View.GONE);
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case MODELAD_LIST:
            case CLIENT_LIST:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case MODELAD_LIST:
            case CLIENT_LIST:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case MODELAD_LIST:
                HemaPageArrayResult<AdImage> aResult = (HemaPageArrayResult<AdImage>) baseResult;
                if (aResult == null || aResult.getObjects() == null)
                    return;
                if (imgs == null) {
                    imgs = new ArrayList<AdImage>();
                } else {
                    imgs.clear();
                }
                imgs.addAll(aResult.getObjects());
                initPager();
                break;
            case CLIENT_LIST:
                HemaPageArrayResult<Client> bResult = (HemaPageArrayResult<Client>) baseResult;
                if (bResult == null || bResult.getObjects() == null)
                    return;
                String role = netTask.getParams().get("role");
                if (page == 0) {// 刷新
                    layoutRefresh.refreshSuccess();
                    layoutRefresh.setLoadmoreable(true);
                    datas.clear();
                    datas.addAll(bResult.getObjects());
                } else {
                    layoutRefresh.loadmoreSuccess();
                    if (bResult.getObjects().size() > 0) {
                        datas.addAll(bResult.getObjects());
                    } else {
                        layoutRefresh.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                refreshData(-1);
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case MODELAD_LIST:
            case CLIENT_LIST:
                if (page == 0) {// 刷新
                    layoutRefresh.refreshFailed();
                } else {
                    layoutRefresh.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败，" + baseResult.getMsg());
                break;
        }
        super.callBackForServerFailed(netTask, baseResult);
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case MODELAD_LIST:
            case CLIENT_LIST:
                if (page == 0) {// 刷新
                    layoutRefresh.refreshFailed();
                } else {
                    layoutRefresh.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败，请稍后再试");
                refreshData(failedType);
                break;
            default:
                break;
        }
    }

    private void refreshData(int failedType) {
        if (adapter == null) {
            adapter = new CmnBookMerchantAdapter(mContext, datas);
            adapter.setItemClickListener(new OnItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    Intent intent = new Intent();
                    Client client = datas.get(position);
                    if (role.equals("11"))
                        intent.setClass(mContext, ZouzouCampsiteMerchantDetailActivity.class);
                    else
                        intent.setClass(mContext, CmnBookMerchantDetailActivity.class);
                    intent.putExtra("client_id", client.getClient_id());
                    mContext.startActivity(intent);
                }
            });
            adapter.setEmptyString("暂时没有商家");
            listView.setAdapter(adapter);
        } else
            adapter.notifyDataSetChanged();
        adapter.setFailtype(failedType);
    }

    @Override
    protected void findView() {
        titleLeftBtn = (ImageButton) findViewById(R.id.title_left_btn);
        tvCity = (TextView) findViewById(R.id.tv_city);
        titleSearch = (ImageView) findViewById(R.id.title_right_img);
        title_text = (TextView) findViewById(R.id.title_text);
        layoutRefresh = (RefreshLoadmoreLayout) findViewById(R.id.layout_refresh);
        listView = (XtomListView) findViewById(R.id.listview);
    }

    @Override
    protected void setListener() {
        title_text.setText("走走");
        titleLeftBtn.setOnClickListener(this);
        tvCity.setOnClickListener(this);
        titleSearch.setOnClickListener(this);
        layoutRefresh.setOnStartListener(new StartListener());
    }

    private class StartListener implements OnStartListener {

        @Override
        public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
            page = 0;
            getNetWorker().ModelADList("2", city.substring(0, city.length() - 1));
            getMerchantList();
        }

        @Override
        public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
            page++;
            getMerchantList();
        }
    }

    private void initPager() {
        ArrayList<String> urls = new ArrayList<>();
        for (AdImage item : imgs) {
            urls.add(item.getImgurl());
        }
        imageCarouselBanner.getLayoutParams().height = XtomWindowSize.getWidth(mContext)/2;
        imageCarouselBanner.onInstance(mContext, urls, R.drawable.ad_show_indicator,
                new ImageCarouselHeadClickListener(mContext, imgs, "2"));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK != resultCode) {
            return;
        }
        switch (requestCode) {
            case 1:
                if (data == null) {
                    return;
                }
                city = getCityName();
                tvCity.setText(city);

                page = 0;
                getNetWorker().ModelADList("2", city.substring(0, city.length() - 1));
                getMerchantList();
                //2016.10.31 start 为了和iOS一致，这里田家、乐乐、走走、农需的地区都单独保存
                XtomSharedPreferencesUtil.save(mContext, "city_zouzou", city);
                //2016.10.31 end 为了和iOS一致，这里田家、乐乐、走走、农需的地区都单独保存
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
